﻿using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Json;
using Codeplex.Data.Internal;

namespace Codeplex.Data.Internal
{
    internal static class MapHelper
    {
        public static T MapToObject<T>(ISerializeProvider serializeProvider, Dictionary<string, byte[]> dbHash, KeyIndexed<string, CompiledAccessor> accessors)
        {
            // if T is ValueType then can't set SetValue
            // must be boxed
            object result = null;

            foreach (var kvp in dbHash)
            {
                var accessor = accessors[kvp.Key];
                if (accessor == null) continue;

                if (result == null)
                {
                    result = (accessor.IsDataContractedType)
                        ? System.Runtime.Serialization.FormatterServices.GetUninitializedObject(typeof(T))
                        : System.Activator.CreateInstance<T>();
                }

                if (!accessor.IsIgnoreSerialize && accessor.IsWritable)
                {
                    var value = serializeProvider.Deserialize(accessor.MemberType, kvp.Value);
                    accessor.SetValueDirect(result, value);
                }
            }

            return (T)result;
        }
    }
}